package com.ipfsemc.ipfsemc.wx;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class QRUtil {

    @Autowired
    private StringUtil stringUtil;                              /* 字符串处理类 */

    /**
     * 二维码生成(不保存图片,以流的形式返回)
     *
     * @param content
     * @param response
     */
    public void encodeQrCode(String content, HttpServletResponse response) {
        if (stringUtil.isEmpty(content)) {
            return;
        }
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");       /* 设置字符集编码类型 */
        hints.put(EncodeHintType.MARGIN, 0);                    /* 设置二维码四周的白色边框 ,默认是4,默认为4的时候白色边框实在是太粗了 */
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 190, 190, hints);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            try {                                               /* 输出二维码图片流 */
                ImageIO.write(image, "png", response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 生成支付二维码
     * @param response 响应
     * @param contents url链接
     * @throws Exception
     */
    public void writerPayImage(HttpServletResponse response, String contents) throws Exception{
        ServletOutputStream out = response.getOutputStream();
        try {
            Map<EncodeHintType,Object> hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,200,200,hints);
            MatrixToImageWriter.writeToStream(bitMatrix,"jpg",out);
        }catch (Exception e){
            throw new Exception("生成二维码失败！");
        }finally {
            if(out != null){
                out.flush();
                out.close();
            }
        }
    }

}

/**
 * 二维码的生成需要借助MatrixToImageWriter类，该类是由Google提供的，可以将该类直接拷贝到源码中使用
 * Created by sam on 16/4/12.
 */
class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}
